package com.jasmine.bjstkserver.server.article.log.viewlog;

import com.jasmine.bjstkserver.manager.ip.IpDTO;
import com.jasmine.bjstkserver.manager.ip.IpManager;
import com.jasmine.bjstkserver.server.article.online.ArticleService;
import com.jasmine.core.constants.BjsConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author jasmineXz
 */
@Component
public class ArticleViewLogViewHandler {

    private static final String VIEW_LIMIT_IP  = "bjstk_article_view_limit_ip:";    // 参数缓存
    private static final String VIEW_LIMIT_ARTICLE_ID  = "_articleid:";    // 参数缓存

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ViewLogService viewLogService;

    @Autowired
    private IpManager ipManager;

    @Autowired
    private RedisTemplate redisTemplate;

    public void execute (ViewLogEntity viewLog) {

        // 相同IP一个小时内访问算一次
        boolean isView = redisTemplate.opsForValue().setIfAbsent(
                VIEW_LIMIT_IP + viewLog.getRemoteAddr().trim() + VIEW_LIMIT_ARTICLE_ID + viewLog.getArticleId(),
                "",
                BjsConstants.Redis.TIME_1_HOURS,
                BjsConstants.Redis.REDIS_SECONDS);

        if (!isView) {
            return;
        }

        IpDTO ipDTO = ipManager.query(viewLog.getRemoteAddr().trim());
        viewLog.setType("VIEW");
        if (ipDTO != null) {
            viewLog.setProvince(ipDTO.getProvince());
            viewLog.setCity(ipDTO.getCity());
        }
        viewLogService.insert(viewLog);
        articleService.viewIncrease(viewLog.getArticleId());

    }
}
